package cz.muni.fi.pv112.cranesimulator.gui.listeners;

import cz.muni.fi.pv112.cranesimulator.scene.Scene;
import cz.muni.fi.pv112.cranesimulator.scene.handlers.SceneHandler;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.glu.GLU;

public class OpenGlListener implements GLEventListener, KeyListener {

    private final GLU glu = new GLU();

    private final Scene sceneHandler = new SceneHandler();

    public OpenGlListener() {
    }

    @Override
    // metoda volana pri vytvoreni okna OpenGL
    public void init(GLAutoDrawable glad) {
        GL2 gl = glad.getGL().getGL2();

        gl.glDisable(GL2.GL_DEPTH_TEST);
        gl.glDisable(GL2.GL_LIGHTING);
        gl.glDisable(GL2.GL_BLEND);

        sceneHandler.init(gl, glu);
    }

    @Override
    // metoda volana pri zatvoreni okna OpenGL
    public void dispose(GLAutoDrawable glad) {

        sceneHandler.unloadModels(glad.getGL());
    }

    @Override
    // metoda volana pri kazdom prekresleni obrazovky 
    public void display(GLAutoDrawable glad) {
        GL2 gl = glad.getGL().getGL2();

        gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);

        gl.glMatrixMode(GL2.GL_MODELVIEW);
        gl.glLoadIdentity();

        sceneHandler.displayScene(gl);
    }

    @Override
    // metoda volana pri zmene velkosti okna
    public void reshape(GLAutoDrawable glad, int x, int y, int width, int height) {
        GL2 gl = glad.getGL().getGL2();
        gl.glViewport(x, y, width, height);
        gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);

        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glLoadIdentity();
        glu.gluPerspective(60, width / (float) height, 0.1, 5000);

    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        sceneHandler.processKeyInput(e, true);
    }

    @Override
    public void keyReleased(KeyEvent e) {
        sceneHandler.processKeyInput(e, false);
    }

    public Scene getSceneHandler() {
        return sceneHandler;
    }

}
